/* 
 * Created on 2006-1-16 
 * Last modified on 2007-6-2
 * Powered by YeQiangWei.com
 */ 
package com.yeqiangwei.net; 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream;
import java.net.HttpURLConnection; 

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

import com.yeqiangwei.util.Validator;

/** 
* 网络文件存取类 
* @author YeQiangWei by 我容易么我 
*/ 
public class UrlFile { 
	
	public UrlFile(){ 
		
	} 
	private static final Logger logger = Logger.getLogger(UrlFile.class.getName());
	
	/** 如果远程文件读取失败用此文件替代 */ 
	public String readerr = ""; 
	
	/** 收集运行哪个结果或错误信息 */ 
	public static String message = ""; 
	
	/** 
	* 采集加缩放图片 
	* @param fileUrl 文件url路径 
	* @param filePathAndName 预创建到本地的文件的绝对路径含文件名已经扩展名 
	* @param width 宽度
	* @param height 高度
	* @throws Exception 
	*/ 
	public static void getImage(String fileUrl, String filePathAndName) throws Exception 
	{ 
		String head = fileUrl.substring(0,fileUrl.indexOf(":"));
		fileUrl = fileUrl.replaceAll(head,head.toLowerCase());
		if(fileUrl.indexOf("http")==-1
				 && fileUrl.indexOf("https")==-1
				 && fileUrl.indexOf("ftp")==-1
				 && fileUrl.indexOf("rtsp")==-1
				 && fileUrl.indexOf("mms")==-1
				
		){
			return ;
		}
		InputStream ins = HttpWrapper.getStream(fileUrl);
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(fileUrl);
		//getMethod.getParams().setSoTimeout(60);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
		int statusCode = httpClient.executeMethod(getMethod);
		if (statusCode != HttpStatus.SC_OK) {
			logger.error("Method failed: "  + getMethod.getStatusLine());           
		}
		Header[] h = getMethod.getResponseHeaders();
		if(Validator.isEmpty(h)){
			return ;
		}
		/*for(int i=0; i<h.length; i++){
			System.out.println(h[i]);
		}
		*/
		//读取内容          
		ins = getMethod.getResponseBodyAsStream();
		BufferedInputStream bis = new BufferedInputStream(ins); 
		BufferedOutputStream bos = null; 
		File f = new File(filePathAndName); 
		bos = new BufferedOutputStream(new FileOutputStream(f));; 
		byte[] b = new byte[1024]; 
		int i = 0; 
		while((i = bis.read(b))>0) 
	    { 
			bos.write(b, 0, i); 
	    }  
		bos.flush(); 
		bis.close(); 
		getMethod.releaseConnection();
		return ; 
	} 
	
	public static void main(String args[]) throws Exception{
		UrlFile.getImage("http://f.yeqiangwei.com/club/s/f34/200706/10063.gif","E:\\abc.jpg");
	}
	
	/** 
	* 根据文件url地址采集并创建到本地 
	* @param fileUrl 文件url路径 
	* @param filePathAndName 预创建到本地的文件的绝对路径含文件名已经扩展名 
	* @return 
	* @throws Exception 
	*/ 
	public boolean createFile(String fileUrl, String filePathAndName) throws Exception 
	{ 
		if(fileUrl.indexOf("http")==-1
				 && fileUrl.indexOf("https")==-1
				 && fileUrl.indexOf("ftp")==-1
				 && fileUrl.indexOf("rtsp")==-1
				 && fileUrl.indexOf("mms")==-1
				
		){
			return false;
		}
		boolean bea = false; 
		java.net.URL urlfile = null; 
		HttpURLConnection httpUrl = null; 
		BufferedInputStream bis = null; 
		BufferedOutputStream bos = null; 
		File f = new File(filePathAndName); 
		try{ 
			//连接指定的网络资源,获取网络输入流 
			urlfile = new java.net.URL(fileUrl); 
			httpUrl = (HttpURLConnection)urlfile.openConnection(); 
			httpUrl.connect(); 
			bis = new BufferedInputStream(httpUrl.getInputStream()); 

		}catch(Exception e){ 
			if(readerr!=null && !readerr.equals("")){ 
				try{ 
					urlfile = new java.net.URL(readerr); 
					httpUrl = (HttpURLConnection)urlfile.openConnection(); 
					httpUrl.connect(); 
					bis = new BufferedInputStream(httpUrl.getInputStream()); 
				}catch(Exception e1){ 
					message = e1.toString(); 
					throw(e1);
				} 
			} 
			message = e.toString(); 
			throw(e);
		} 
		
		try{ 
			bos = new BufferedOutputStream(new FileOutputStream(f));; 
			byte[] b = new byte[1024]; 
			int i = 0; 
			while((i = bis.read(b))>0){ 
				bos.write(b, 0, i); 
		    }  
			bea = true; 
			message = fileUrl+" 采集成功！文件已存储至："+filePathAndName; 
		}catch(Exception e){ 
			bea = false; 
			message = e.toString(); 
			throw(e);
		}finally{ 
			try{ 
				bos.flush(); 
				bis.close(); 
				httpUrl.disconnect(); 
			}catch(Exception e){ 
				message = e.toString(); 
				throw(e);
			} 
		}
		return bea; 
	} 

	public void setReaderr(String readerr) { 
		this.readerr = readerr; 
	} 

	/*
	public static void main(String args[]) throws Exception{ 
		//远程文件路径 
		String s1 = "www.100分求儿歌一首.，很想听，分不够可以加"; 
		//本地存放路径 
		String s2 = "E:\\1.jpg"; 
		com.yeqiangwei.net.UrlFile uf = new com.yeqiangwei.net.UrlFile();
		uf.createFile(s1, s2);
		System.out.println(uf.getMessage());
	}
	*/
}